import uuid


from flask_login import logout_user,login_user

from flask_restful import Resource, reqparse, marshal_with
from sqlalchemy import or_
from flask import render_template,jsonify
from apps.common.result import Result
from apps.ext import login_manager, db, mail, cache
from apps.user.fields import result
from apps.user.models import User


"""
Flask-Login要求程序实现一个回调函数，主要是获取存储到session中user对象
"""
@login_manager.user_loader
def _login_user(uid):
    return User.query.get(uid)


class UserRegisterApi(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('username',type=str,required=True)
        self.parser.add_argument('password', type=str, required=True)
        self.parser.add_argument('email', type=str, required=True)
        self.parser.add_argument('phone', type=str, required=True)

    def post(self):
        """注册"""
        args = self.parser.parse_args()
        username = args.get('username')
        password = args.get('password')
        phone = args.get('phone')
        email = args.get('email')

        user = User.query.filter(or_(User.username==username,User.email==email,User.phone==phone)).all()
        if not user:
            try:
                user = User()
                user.username = username
                user.email = email
                user.phone = phone
                user.password = password
                db.session.add(user)
                db.session.commit()
            except:
                db.session.rollback()

            # 发送邮件
            to_email = email
            token = uuid.uuid4()
            uid = User.query.filter(username=username).first().uid
            cache.set(token,uid,timeout=10*60)
            send_register_active_email.delay(to_email, username, token)
        else:
            pass

        data = {
            'status':200,
            'success':'success'
        }
        return jsonify(data)

    def put(self):
        """修改"""
        pass

    def delete(self):
        """注销"""
        pass

class UserLoginApi(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('account', type=str, required=True,help='用户名,手机号,邮箱,且不能为空')
        self.parser.add_argument('password', type=str, required=True)
        self.parser.add_argument('remember', type=str)

    @marshal_with(result)
    def post(self):
        args = self.parser.parse_args()
        account = args.get('account')
        password = args.get('password')
        remember = args.get('remember')

        if not all([account,password]):
            return jsonify("数据不完整")
        user = User.query.filter(or_(User.username == account, User.email == account, User.phone == account)).first()
        if not user:
            return jsonify("账号错误")
        if not user.vertify_password(password):
            return jsonify("密码错误")

        # 登录的方法
        if remember == 'on':
            login_user(user,remember=True)
        else:
            login_user(user,remember=False)

        username = user.username
        data = {
            'user':username
        }
        return Result.get_success_result_obj(data)



class UserLogoutApi(Resource):
    def post(self):
        logout_user()

"""
安全问题考虑:
生成token
redis缓存{token:uid}
"""
class UserActiveApi(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('token', type=str, required=True,)

    def get(self):
        args = self.parser.parse_args()
        token = args.get('token')
        uid = cache.get(token)
        if uid:
            try:
                User.query.get(uid).update({User.is_active: 1})
                db.session.commit()
            except:
                db.session.rollback()
            return

